import { AudioClip } from "cc";
import { LocalData } from "../common/LocalData";
import { EnCommonModuleName } from "../const/EnCommon";
import { Handler } from "../event/Handler";
import { GameData } from "../GameData";
import { AudioData } from "./AudioData";
import { AudioMgr } from "./AudioMgr";


export class AudioManager {
    private static mgr: AudioManager;

    static get instance() {
        if (this.mgr == null) {
            this.mgr = new AudioManager();
        }

        return this.mgr;
    }

    static destory() {
        if (this.mgr) {
            this.mgr = null;
        }
    }

    data: AudioData = new AudioData();
    private curBgName: string = null;

    // 播放背景音乐
    playBgm(filename: string) {
        const localData = LocalData.instance.GetItemCommon(EnCommonModuleName.Music);
        if (!localData || localData == "0") {
            let playbgm = Handler.create(this.playbgmcallback, this, [filename]);
            this.data.loadBgmAudio(filename, playbgm);
        }
    }

    // 播放音效
    playEffect(filename: string) {
        if (GameData.isPlayAudio == false) {
            return;
        }
        const localData = LocalData.instance.GetItemCommon(EnCommonModuleName.Sound)
        if (!localData || localData == "0") {
            let playeffect = Handler.create(this.playeffectcallback, this, [filename]);
            let result = this.data.loadEffectAudio(filename, playeffect);
            if (cc.isValid(result)) {
                cc.audioEngine.stopEffect(result.id);
                let id = cc.audioEngine.playEffect(result.audio, false);
                this.data.seteffectMap(filename, id, result.audio);
            }
        }
    }

    // bgm音量
    volumeBgm(value: number) {
        let curvalue = cc.audioEngine.getMusicVolume();
        cc.audioEngine.setMusicVolume(curvalue + value);
    }

    stopEffect()
    {
        AudioMgr.inst.stop();
    }

    // effect音量
    volumeEffect(value: number) {
        AudioMgr.inst.setVolume(value);
    }

    // 停止bgm
    stopBgm() {
        AudioMgr.inst.stopMusic();
    }

    // 暂停bgm
    pauseBgm() {
        AudioMgr.inst.stopMusic();
    }

    // 恢复bgm
    resumeBgm() {
        if (!cc.audioEngine.isMusicPlaying())
            cc.audioEngine.resumeMusic();
    }

    //重置bgm
    resetBgm() {
        this.playBgm(this.curBgName);
    }

    private playbgmcallback(filename: string, clip: AudioClip) {
        if (clip) {
            if(this.curBgName)
            {
                AudioManager.instance.stopBgm();
            }
            this.curBgName = filename;
            AudioMgr.inst.playMusic(clip, 0.4);
            AudioMgr.inst.musicSource.loop = true;
        }
    }

    private playeffectcallback(filename: string, clip: AudioClip) {
        if (clip == null) {
            console.error("加载或解析音效文件失败：" + filename);
            return;
        }
        AudioMgr.inst.play(clip);
    }
}